package hu.mapro.gwtui.gxt.client.fieldseditor;

import hu.mapro.gwtui.client.Action;

import com.google.gwt.editor.client.CompositeEditor;
import com.google.gwt.editor.client.EditorDelegate;
import com.google.gwt.user.client.ui.ResizeComposite;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;

public class FieldsEditorComponent<T> extends ResizeComposite implements CompositeEditor<T, Object, FieldsEditorBuilder<T, ?>.EditorField<Object>.LeafEditor> {

	private final FieldsEditorBuilder<T, ?> fieldsEditor;
	private EditorChain<Object, FieldsEditorBuilder<T, ?>.EditorField<Object>.LeafEditor> chain;

	public FieldsEditorComponent(FieldsEditorBuilder<T, ?> fieldsEditor, VerticalLayoutContainer vlc) {
		this.fieldsEditor = fieldsEditor;
		initWidget(vlc);
	}
	
	
	@Override
	public void setDelegate(EditorDelegate<T> delegate) {
	}

	@Override
	public void flush() {
		for (FieldsEditorBuilder<T, ?>.EditorField<?> field : this.fieldsEditor.fields) {
			field.flush();
		}
	}

	@Override
	public void onPropertyChange(String... paths) {
		// TODO Auto-generated method stub
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void setValue(T value) {
		for (FieldsEditorBuilder<T, ?>.EditorField<?> field : this.fieldsEditor.fields) {
			
			FieldsEditorBuilder<T, ?>.EditorField<Object> fieldObject = (FieldsEditorBuilder.EditorField)field;
			
			FieldsEditorBuilder<T, ?>.EditorField<Object>.LeafEditor leafEditor = fieldObject.leafEditor;
			leafEditor.edit(value);
			
			Object object = fieldObject.getValue(value);
			if (chain!=null) {
				chain.attach(object, leafEditor);
			}
		}
	}
	
	public Action createFocusAction() {
		return new Action() {
			@Override
			public void perform() {
				focus();
			}
		};
	}


	@Override
	public FieldsEditorBuilder<T, ?>.EditorField<Object>.LeafEditor createEditorForTraversal() {
		return null;
	}


	@Override
	public String getPathElement(FieldsEditorBuilder<T, ?>.EditorField<Object>.LeafEditor subEditor) {
		return subEditor.getPathElement();
	}


	@Override
	public void setEditorChain(
			com.google.gwt.editor.client.CompositeEditor.EditorChain<Object, FieldsEditorBuilder<T, ?>.EditorField<Object>.LeafEditor> chain) {
		this.chain = chain;
		
	}


	public void focus() {
		FieldsEditorComponent.this.fieldsEditor.fields.get(0).editorField.focus();
	}


	public void checkDirty() {
		fieldsEditor.checkDirty();
	}


	}